<template>
  <div class="workflow-status-panel">
    <div class="header">
      <h2 class="title">工作流程实时状态</h2>
    </div>
    
    <div class="content">
      <div class="workflow-table">
        <div class="table-header">
          <div class="col-time">时间</div>
          <div class="col-flow-id">流水单号</div>
          <div class="col-flow-send">发送</div>
          <div class="col-flow-recv">接收</div>
          <div class="col-subject">主题</div>
          <div class="col-content">详细内容</div>
        </div>
        
        <div class="table-body" ref="tableBody">
          <div 
            v-for="(item, index) in workFlowStatusList" 
            :key="`${item.time}-${index}`"
            class="table-row"
            :class="{ 
              'selected': selectedIndex === index,
              'connecting': isConnectingStatus(item.content),
              'failed': isFailedStatus(item.content)
            }"
            @click="selectItem(index)"
          >
            <div class="col-time">
              <span class="time">{{ item.time }}</span>
            </div>
            <div class="col-flow-id">
              <span class="flow-id">{{ item.flowId }}</span>
            </div>
            <div class="col-flow-send">
              <span class="flow-send">{{ item.flowSend }}</span>
            </div>
            <div class="col-flow-recv">
              <span class="flow-recv">{{ item.flowRecv }}</span>
            </div>
            <div class="col-subject">
              <span class="subject">{{ item.subject }}</span>
            </div>
            <div class="col-content">
              <span class="content" :class="getStatusClass(item.content)">
                {{ item.content }}
              </span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="workFlowStatusList.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">暂无工作流程信息</div>
      </div>
      
      <!-- 错误状态 -->
      <div v-if="error" class="error-state">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ error }}</div>
        <el-button type="primary" size="small" @click="retry">重试</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch} from 'vue'
import { ElButton } from 'element-plus'
import { useMQTT } from '../composables/useMQTT'
import { MQTT_CONFIG } from '../config/mqtt'

// 响应式数据
const selectedIndex = ref<number>(-1)
const tableBody = ref<HTMLElement>()
const accumulatedWorkFlowData = ref<Array<{
  time: string
  flowId: string
  flowSend: string
  flowRecv: string
  subject: string
  content: string
}>>([])

// 使用MQTT组合式函数
const {
  workFlowStatus,
  error,
  connect
} = useMQTT()

// 监听工作流程状态变化，自动追加新数据
watch(workFlowStatus, (newWorkFlowStatus) => {
  if (newWorkFlowStatus && newWorkFlowStatus.data) {
    console.log('工作流程状态已更新:', newWorkFlowStatus)
    // 将新数据追加到累积数据中
    accumulatedWorkFlowData.value.push(...newWorkFlowStatus.data)
    
    // 判断数据量，超过20条时清空列表
    if (accumulatedWorkFlowData.value.length > 20) {
      console.log('工作流程数据量超过20条，清空列表')
      accumulatedWorkFlowData.value = []
      selectedIndex.value = -1
    }
  }
})

// 计算属性 - 工作流程状态列表（显示累积的所有数据）
const workFlowStatusList = computed(() => {
  return accumulatedWorkFlowData.value
})

// 判断是否为连接中状态
const isConnectingStatus = (content: string): boolean => {
  return content.includes('正在连接') || content.includes('连接中')
}

// 判断是否为失败状态
const isFailedStatus = (content: string): boolean => {
  return content.includes('失败') || content.includes('错误')
}

// 获取状态样式类
const getStatusClass = (content: string): string => {
  if (isConnectingStatus(content)) {
    return 'status-connecting'
  } else if (isFailedStatus(content)) {
    return 'status-failed'
  } else if (content.includes('成功')) {
    return 'status-success'
  } else if (content.includes('警告')) {
    return 'status-warning'
  } else {
    return 'status-info'
  }
}

// 选择项目
const selectItem = (index: number): void => {
  selectedIndex.value = index
  console.log('选中工作流程项:', workFlowStatusList.value[index])
}

// 重试
const retry = (): void => {
  // 重试逻辑可以在这里实现
}

// 初始化
const initialize = async (): Promise<void> => {
  // 连接MQTT
  await connect({
    brokerUrl: MQTT_CONFIG.BROKER_URL,
    username: MQTT_CONFIG.USERNAME,
    password: MQTT_CONFIG.PASSWORD,
    clientId: `${MQTT_CONFIG.CLIENT_ID_PREFIX}-${Date.now()}`
  })
}

// 清理
const cleanup = (): void => {
  // useMQTT 会自动清理
}

// 生命周期
onMounted(() => {
  initialize()
})

onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
.workflow-status-panel {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafafa;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.workflow-table {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  background: #f5f5f5;
  border-bottom: 2px solid #d9d9d9;
  font-weight: 600;
  color: #333;
}

.table-body {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #f8f9fa;
}

.table-row.selected {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.table-row.connecting {
  background-color: #fff7e6;
}

.table-row.failed {
  background-color: #fff2f0;
}

.col-time {
  width: 180px;
  padding: 12px 16px;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.col-flow-id {
  width: 120px;
  padding: 12px 16px;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.col-flow-send {
  width: 120px;
  padding: 12px 16px;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.col-flow-recv {
  width: 120px;
  padding: 12px 16px;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.col-subject {
  width: 100px;
  padding: 12px 16px;
  border-right: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.col-content {
  flex: 1;
  padding: 12px 16px;
  min-width: 0;
}

.time {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  color: #666;
}

.flow-id {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.flow-send {
  font-size: 14px;
  color: #333;
}

.flow-recv {
  font-size: 14px;
  color: #333;
}

.subject {
  font-size: 14px;
  color: #333;
}

.content {
  font-size: 14px;
  color: #333;
}

.status-connecting {
  color: #fa8c16;
  font-weight: 500;
}

.status-failed {
  color: #f5222d;
  font-weight: 500;
}

.status-success {
  color: #52c41a;
  font-weight: 500;
}

.status-warning {
  color: #faad14;
  font-weight: 500;
}

.status-info {
  color: #1890ff;
  font-weight: 500;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
}

.error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #f5222d;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-text {
  font-size: 16px;
  margin-bottom: 16px;
}

/* 滚动条样式 */
.table-body::-webkit-scrollbar {
  width: 8px;
}

.table-body::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.table-body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
